import { getSourceUrl, getLyric } from 'api/api'
import { playMode } from 'common/js/config'
import { shuffle } from 'common/js/util'

function findIndex(list,song) {
    return list.findIndex(item=> {
        return item.id === song.id
    })
}

const actions = {
    getCurrentSong({state, commit},{index, list}) {      
        commit('SET_SEQUENCE_LIST',list)
        if(state.mode === playMode.random) {
            let randomList = shuffle(list)
            commit('SET_PLAY_LIST',randomList)
            index = findIndex(randomList,list[index])
        }else {
            commit('SET_PLAY_LIST',list)
        }   
        commit('SET_CURRENT_INDEX',index)
        commit('TOGGLE_PLAYER',true)
    },
    getSongSource({state, commit}) {
        let id = state.playlist[state.currentIndex].id
        let _getSourceUrl = getSourceUrl({id})
        let _getLyric = getLyric({id})
        Promise.all([_getSourceUrl, _getLyric]).then(res=> {
            commit('GET_SONG_SRC',res[0].data[0].url)
            setTimeout(() => {
                commit('GET_SONG_LYRIC',res[1].lrc.lyric)
            }, 20);
            
        })
    }
}   

export default actions